<template>
  <div class="household-selector">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="社区" required>
          <el-select
            v-model="formData.communityId"
            placeholder="请选择社区"
            clearable
            style="width: 100%"
            @change="handleCommunityChange"
            :loading="loading.community"
          >
            <el-option
              v-for="item in communityList"
              :key="item.id"
              :label="item.communityName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="楼栋" required>
          <el-select
            v-model="formData.buildingId"
            placeholder="请选择楼栋"
            clearable
            style="width: 100%"
            @change="handleBuildingChange"
            :loading="loading.building"
            :disabled="!formData.communityId"
          >
            <el-option
              v-for="item in buildingList"
              :key="item.id"
              :label="item.buildingName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="单元" required>
          <el-select
            v-model="formData.unitId"
            placeholder="请选择单元"
            clearable
            style="width: 100%"
            @change="handleUnitChange"
            :loading="loading.unit"
            :disabled="!formData.buildingId"
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="房户" required>
          <el-select
            v-model="formData.householdId"
            placeholder="请选择房户"
            clearable
            style="width: 100%"
            @change="handleHouseholdChange"
            :loading="loading.household"
            :disabled="!formData.unitId"
          >
            <el-option
              v-for="item in householdList"
              :key="item.id"
              :label="item.roomNumber"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { communityApi } from '@/api/community'
import { buildingApi } from '@/api/building'
import { unitApi } from '@/api/unit'
import { householdApi } from '@/api/household'

// 定义组件属性
interface Props {
  modelValue: {
    communityId?: number
    buildingId?: number
    unitId?: number
    householdId?: number
  }
}

// 定义组件事件
interface Emits {
  (e: 'update:modelValue', value: Props['modelValue']): void
  (e: 'change', value: Props['modelValue']): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单数据
const formData = reactive({
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  householdId: undefined as number | undefined
})

// 列表数据 - 使用ref而不是reactive，模仿住户管理页面
const communityList = ref<any[]>([])
const buildingList = ref<any[]>([])
const unitList = ref<any[]>([])
const householdList = ref<any[]>([])

// 加载状态
const loading = reactive({
  community: false,
  building: false,
  unit: false,
  household: false
})

// 监听props变化，同步到formData
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    formData.communityId = newVal.communityId
    formData.buildingId = newVal.buildingId
    formData.unitId = newVal.unitId
    formData.householdId = newVal.householdId
  }
}, { immediate: true, deep: true })

// 监听formData变化，同步到父组件
watch(formData, (newVal) => {
  emit('update:modelValue', { ...newVal })
  emit('change', { ...newVal })
}, { deep: true })

// 组件挂载时加载社区列表
onMounted(() => {
  loadCommunityList()
})

/**
 * 加载社区列表
 */
const loadCommunityList = async () => {
  try {
    loading.community = true
    const response = await communityApi.getCommunityList()
    if (response.code === 200) {
      // 过滤掉没有有效id的数据，遵循Element Plus组件编码规范
      communityList.value = (response.data || []).filter((item: any) => item.id != null)
    } else {
      ElMessage.error(response.message || '加载社区列表失败')
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
    ElMessage.error('加载社区列表失败')
  } finally {
    loading.community = false
  }
}

/**
 * 社区选择变化处理
 */
const handleCommunityChange = async (communityId: number) => {
  console.log('社区选择变化，communityId:', communityId)
  
  // 清空下级选择
  formData.buildingId = undefined
  formData.unitId = undefined
  formData.householdId = undefined
  buildingList.value = []
  unitList.value = []
  householdList.value = []
  
  if (!communityId) {
    console.log('communityId为空，直接返回')
    return
  }
  
  try {
    loading.building = true
    console.log('开始加载楼栋列表，communityId:', communityId)
    
    // 使用专门的下拉框接口，返回数组格式数据
    const response = await buildingApi.getBuildingsByCommunity(communityId)
    console.log('楼栋API响应:', response)
    
    if (response.code === 200) {
      // 过滤掉没有有效id的数据，遵循Element Plus组件编码规范
      buildingList.value = (response.data || []).filter((item: any) => item.id != null)
      console.log('过滤后的楼栋列表:', buildingList.value)
    } else {
      console.error('楼栋API返回错误:', response.message)
      ElMessage.error(response.message || '加载楼栋列表失败')
    }
  } catch (error) {
    console.error('加载楼栋列表失败:', error)
    ElMessage.error('加载楼栋列表失败')
  } finally {
    loading.building = false
  }
}

/**
 * 楼栋选择变化处理
 */
const handleBuildingChange = async (buildingId: number) => {
  console.log('楼栋选择变化，buildingId:', buildingId)
  
  // 清空下级选择
  formData.unitId = undefined
  formData.householdId = undefined
  unitList.value = []
  householdList.value = []
  
  if (!buildingId) {
    return
  }
  
  try {
    loading.unit = true
    console.log('开始加载单元列表，buildingId:', buildingId)
    
    // 使用专门的下拉框接口，返回数组格式数据
    const response = await unitApi.getUnitsByBuilding(buildingId)
    console.log('单元API响应:', response)
    
    if (response.code === 200) {
      // 过滤掉没有有效id的数据，遵循Element Plus组件编码规范
      unitList.value = (response.data || []).filter((item: any) => item.id != null)
      console.log('过滤后的单元列表:', unitList.value)
    } else {
      ElMessage.error(response.message || '加载单元列表失败')
    }
  } catch (error) {
    console.error('加载单元列表失败:', error)
    ElMessage.error('加载单元列表失败')
  } finally {
    loading.unit = false
  }
}

/**
 * 单元选择变化处理
 */
const handleUnitChange = async (unitId: number) => {
  console.log('单元选择变化，unitId:', unitId)
  
  // 清空下级选择
  formData.householdId = undefined
  householdList.value = []
  
  if (!unitId) {
    return
  }
  
  try {
    loading.household = true
    console.log('开始加载房户列表，unitId:', unitId)
    
    // 使用专门的下拉框接口，返回数组格式数据
    const response = await householdApi.getHouseholdsByUnit(unitId)
    console.log('房户API响应:', response)
    
    if (response.code === 200) {
      // 过滤掉没有有效id的数据，遵循Element Plus组件编码规范
      householdList.value = (response.data || []).filter((item: any) => item.id != null)
      console.log('过滤后的房户列表:', householdList.value)
    } else {
      ElMessage.error(response.message || '加载房户列表失败')
    }
  } catch (error) {
    console.error('加载房户列表失败:', error)
    ElMessage.error('加载房户列表失败')
  } finally {
    loading.household = false
  }
}

/**
 * 房户选择变化处理
 */
const handleHouseholdChange = (householdId: number) => {
  // 房户选择完成，可以在这里添加额外的处理逻辑
  console.log('选择的房户ID:', householdId)
  // 触发change事件，通知父组件房户选择已完成
  emit('change', { ...formData })
}

/**
 * 重置选择器
 */
const reset = () => {
  formData.communityId = undefined
  formData.buildingId = undefined
  formData.unitId = undefined
  formData.householdId = undefined
  buildingList.value = []
  unitList.value = []
  householdList.value = []
}

// 暴露方法给父组件
defineExpose({
  reset
})
</script>

<style lang="scss" scoped>
.household-selector {
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .el-select {
    width: 100%;
  }
}
</style>
